package com.scalar.forecast.salesPersonSetup.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.salesPersonSetup.forms.SalesPersonSetupForm;
import com.scalar.forecast.salesPersonSetup.dao.SalesPersonSetupDAO;
import com.scalar.ScalarException;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.forecast.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/** Process the request to save sales person setup details.
 *
 * Created by Gandhi.
 * Date: Feb 8, 2005
 * Time: 7:00:25 PM
 */
public class SalesPersonSetupSaveCommand extends ActionCommand {

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) throws ScalarException
    {

            SalesPersonSetupForm salesPersonSetupForm = (SalesPersonSetupForm)form;
            int levelOrder = salesPersonSetupForm.getForecastLevelOrder() + 1;
            HttpSession session = request.getSession();
            HashMap info = new HashMap();
            HashMap errors = new HashMap();
            boolean isSalesPersonExits = false;
            boolean isUserExists = false;
            boolean success = false;
            int  salesPersonId = -1;
            String userId = null;
            String userIds[] = null;
            DBTransaction dbTransaction = null;
            dbTransaction = DBTransaction.getInstance();
            if( dbTransaction != null )
            {
                dbTransaction.begin();
            }
            try
            {
                    salesPersonId = salesPersonSetupForm.getExistingSalesPersonId();
                    //userId = salesPersonSetupForm.getExistingUserId();
                    userIds = salesPersonSetupForm.getExistingUserIds();
                    //checking whether the users are already mapped to other salespersons..
                    int userIdsLen  = userIds.length;
                    for ( int i=0; i < userIdsLen; i++ )
                    {
                        userId = userIds[i];
                        if ( SalesPersonSetupDAO.isUserIdExists( dbTransaction , salesPersonId, userId) )
                        {
                            errors.put ("User '" + userId + "' already mapped to other Sales Person", null);
                            request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                            isUserExists = true;
                        }
                    }
                    isSalesPersonExits = SalesPersonSetupDAO.isSalesPersonIdExist( dbTransaction , salesPersonId );
                    //isUserExists = SalesPersonSetupDAO.isUserIdExists( dbTransaction , salesPersonId, userId);
                    if( isUserExists == false )
                    {
                            if( isSalesPersonExits == false)
                            {
                                //SalesPersonSetupDAO.insertSalesPersonInfo( dbTransaction , salesPersonSetupForm , true );
                                SalesPersonSetupDAO.saveSalesPersonInfo( dbTransaction, salesPersonSetupForm );
                                info.put ("Sales Person Setup information has been saved successfully", null);
                                request.setAttribute(SessionKeys.INFO_MESSAGES, info);
                                success = true;

                                salesPersonSetupForm.setExistingSalesPersonId( -1 );
                                salesPersonSetupForm.setExistingUserId( null );
                                salesPersonSetupForm.setExistingUserIds( null );
                                salesPersonSetupForm.setForecastLevelOrder( -1 );
                                salesPersonSetupForm.setManagerId( -1 );
                            }
                            else
                            {

								if ( ( salesPersonSetupForm.getForecastLevelOrder () != SalesPersonSetupDAO.getLevelOrder ( salesPersonSetupForm.getExistingSalesPersonId () ) ) && SalesPersonSetupDAO.hasSubordinatesForTheSalesPerson ( dbTransaction, salesPersonSetupForm.getExistingSalesPersonId () ) )
								{
                                	errors.put ( "Sales Person Setup information <strong>not saved</strong> since the Sales Person has subordinates", null );
									request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
								}
								else
								{
									//SalesPersonSetupDAO.insertSalesPersonInfo( dbTransaction , salesPersonSetupForm , false );
                                    SalesPersonSetupDAO.saveSalesPersonInfo( dbTransaction, salesPersonSetupForm);
                                    info.put ("Sales Person Setup information has been Updated successfully", null);
									request.setAttribute(SessionKeys.INFO_MESSAGES, info);
									salesPersonSetupForm.setExistingSalesPersonId( -1 );
									salesPersonSetupForm.setExistingUserId( null );
                                    salesPersonSetupForm.setExistingUserIds( null );
                                    salesPersonSetupForm.setForecastLevelOrder( -1 );
									salesPersonSetupForm.setManagerId( -1 );
								}
                                success = true;


                            }
                    }
                    /*else
                    {
                            info.put ("User already mapped to other Sales Person", null);
                            request.setAttribute(SessionKeys.INFO_MESSAGES, info);
                    }*/
            }

            catch(ScalarException e)
            {
                errors.put ("Sales Person Could not saved into Data Base", null);
                request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);

                System.out.println ("Exception while storing Sales Person.. \n" + e.getRootCause().getMessage() + "\nRolling back");
                e.printStackTrace();
            }
            finally
            {
                // Rollback or Commit the Transaction
                try
                    {
                        if (success == true) {
                            dbTransaction.commit();
                        }else{
                            //errors.put ("Sales Person Could not saved into Data Base", null);
                            //request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                            dbTransaction.rollback();
                        }
                    }
                    catch (DBXException e)
                    {
                        e.printStackTrace();
                    }
            }
            ArrayList salesPersonsList = SalesPersonSetupDAO.loadSalesPersonsList( null );
            if ( salesPersonsList.size() > 0  )
            {
                request.setAttribute("showList", "true");
                request.setAttribute("salesPersonsList",  salesPersonsList );
            }

            request.setAttribute("salesPersonList", SalesPersonSetupDAO.getSalesPersonList());
            request.setAttribute("userList", SalesPersonSetupDAO.getUserList());
            request.setAttribute("levelList", SalesPersonSetupDAO.getLevelList());
            request.setAttribute("mgrList", SalesPersonSetupDAO.getManagerList(levelOrder, salesPersonSetupForm.getExistingSalesPersonId ()));

            ActionForward actionForward = mapping.findForward("success");
            return actionForward;
    }
}
